<template>
  <BasicModal
    v-bind="$attrs"
    @ok="handleSubmint"
    okText="提交"
    :showOkBtn="props.formType.operationType !== 2"
    @register="register"
    :title="modalTitle"
    width="40%"
    :min-height="500"
    @visible-change="handleVisibleChange"
  >
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerFormByDrive">
        <template #slotTabsForm="{ model, field }">
          <!-- <tabsForm :tabsList="model[field]" /> -->
          <div class="tabs-form">
            <Tabs v-model:activeKey="activeKey">
              <Tabs.TabPane
                :tab="item.Title"
                v-for="item in model[field]"
                :key="item.Title"
                :forceRender="true"
              >
                <BasicForm @register="item.Form[0]" />
              </Tabs.TabPane>
            </Tabs>
          </div>
        </template>
      </BasicForm>
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { BasicModal, useModal } from '/@/components/Modal';
  import { cloneDeep, omit } from 'lodash-es';
  import { buildUUID } from '/@/utils/uuid';
  import { computed, nextTick, reactive, ref, h } from 'vue';
  import { BasicForm, FormSchema, useForm, FormProps } from '/@/components/Form/index';
  import { Tabs } from 'ant-design-vue';
  // import fileWay from '/@/views/project/tag/components/fileWay.vue';
  import { ParamsByDriveModel, FileAnalysisModel, ResByFileModel } from './type';
  // import tabsForm from './tabsForm.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { getFormErrorMessage, checkName, checkIp, checkVaid } from '/@/utils/index';

  import {
    getDefaultDriverConfig,
    getworkmodel,
    getplcpathtype,
    gettemplatecollection,
  } from '/@/api/tag/index';

  const props = defineProps({
    formType: {
      type: Object,
      default: () => {},
    },
    // 使用场景
    type: {
      type: String,
      default: '',
    },
  });

  // 旧的表单
  let oldArgument: any = {};
  // 文档模式内容
  let fileAnalysisArr: FileAnalysisModel[] = [];
  let workModelOptions = reactive([]);
  let plcpathtypeOptions = reactive([]);
  let templateOptions = reactive([]);
  const { createConfirm, createMessage } = useMessage();
  // 驱动配置表单内容
  let schemasByDrive: FormSchema[] = [
    {
      field: 'name',
      component: 'Input',
      label: `${props.type === 'template' ? '模板' : ''}设备名称`,
      // helpMessage: '总长度为200字符，一个中文等于8个字符，数字/字母/英文下划线占1个字符',
      dynamicDisabled: () => {
        return props.formType.operationType === 2;
      },
      colProps: {
        span: 24,
      },
      rules: [
        {
          required: true,
          validator: async (_rule, value) =>
            checkName(value, `${props.type === 'template' ? '模板' : ''}设备名称`),
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'preconfiguration',
      component: 'Cascader',
      label: '设备类型：',
      dynamicDisabled: () => {
        return props.formType.operationType === 2;
      },
      colProps: {
        span: 24,
      },
      rules: [
        {
          required: true,
          // message: '请选择预配置',
          validator: async (_rule, value) => {
            if (!value) {
              /* eslint-disable-next-line */
              return Promise.reject('请选择设备类型');
            }
            return Promise.resolve();
          },
          trigger: ['change', 'blur'],
        },
      ],
      componentProps: {
        // api: getDefaultDriverConfig,
        // labelField: 'Name',
        // valueField: 'PreDriverName',
        // dataField: 'Data',
        // childrenField: 'Children',
        // // immediate: true,
        disabled: props.type === 'template',
        options: [],
        fieldNames: { label: 'Name', value: 'Id', children: 'Children' },
        onChange: (_e, selectedOptions) => {
          if (selectedOptions && selectedOptions.length > 0) {
            let val = selectedOptions[selectedOptions.length - 1];
            setNewForm(val);
          }
        },
      },
    },
    {
      field: 'addressExtend',
      component: 'RadioGroup',
      label: '地址获取方式：',
      dynamicDisabled: () => {
        return props.formType.operationType === 2;
      },
      colProps: {
        span: 24,
      },
      rules: [
        {
          required: true,
          validator: async (_rule, value) => {
            if (['', null, undefined].indexOf(value) >= 0) {
              /* eslint-disable-next-line */
              return Promise.reject('请选择地址获取方式');
            }
            return Promise.resolve();
          },
          trigger: ['change', 'blur'],
        },
      ],
      defaultValue: 0,
      componentProps: {
        disabled: true,
        options: [
          {
            label: '输入模式',
            value: 0,
          },
          {
            label: '从列表获取',
            value: 1,
          },
        ],
      },
    },
    {
      field: 'assemblyName',
      component: 'Input',
      label: '程序集名：',
      dynamicDisabled: () => {
        return props.formType.operationType === 2;
      },
      colProps: {
        span: 24,
      },
      rules: [
        {
          required: true,
          message: '请输入程序集名',
          trigger: ['change', 'blur'],
        },
      ],
      componentProps: {
        disabled: true,
      },
    },
    {
      field: 'className',
      component: 'Input',
      label: '类全名：',
      dynamicDisabled: () => {
        return props.formType.operationType === 2;
      },
      colProps: {
        span: 24,
      },
      rules: [
        {
          required: true,
          message: '请输入类全名',
          trigger: ['change', 'blur'],
        },
      ],
      componentProps: {
        disabled: true,
      },
    },
    {
      field: 'DriverNO',
      component: 'Input',
      label: '设备编码：',
      colProps: {
        span: 24,
      },
      defaultValue: buildUUID(),
      dynamicDisabled: () => {
        return props.formType.operationType === 2;
      },
      rules: [
        {
          required: true,
          message: '请输入设备编码',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'PDU',
      component: 'Input',
      label: '单次采集数据块：',
      colProps: {
        span: 24,
      },
      dynamicDisabled: () => {
        return props.formType.operationType === 2;
      },
      rules: [
        {
          required: true,
          message: '请输入单次采集数据块',
          trigger: ['change', 'blur'],
        },
      ],
      componentProps: {
        disabled: true,
      },
    },
    {
      field: 'Description',
      component: 'InputTextArea',
      label: '描述：',
      dynamicDisabled: () => {
        return props.formType.operationType === 2;
      },
      colProps: {
        span: 24,
      },
      componentProps: {
        showCount: true,
        maxlength: 500,
      },
    },
    {
      field: 'TemplateId',
      component: 'Select',
      label: '模板：',
      colProps: {
        span: 24,
      },
      dynamicDisabled: () => {
        return [1, 2].indexOf(props.formType.operationType) >= 0;
      },
      ifShow: () => {
        return props.type !== 'template';
      },
      componentProps: {
        placeholder: '请选择模板',
        options: [],
        fieldNames: { label: 'Name', value: 'TemplateId', key: 'Key' },
        onChange: (e) => {
          setFieldsValueByTemplate(e);
        },
      },
    },
    {
      field: 'TemplateSync',
      component: 'RadioGroup',
      label: '是否与模板同步：',
      colProps: {
        span: 24,
      },
      dynamicDisabled: () => {
        return props.formType.operationType === 2;
      },
      ifShow: ({ values }) => {
        return props.type !== 'template' && ['', null, undefined].indexOf(values.TemplateId) === -1;
      },
      componentProps: {
        onChange: ({ target }) => {
          if (!target || target.value === '0') return;
          createConfirm({
            iconType: 'warning',
            okText: '确认',
            title: () => h('span', '温馨提示'),
            content: () => h('span', `同步后修改的信息会清除，并与模板内容一致,请确认`),
            onOk: () => {},
            onCancel: () => {
              setFieldsValueByDrive({ TemplateSync: '0' });
            },
          });
        },
        options: [
          {
            label: '是',
            value: '1',
          },
          {
            label: '否',
            value: '0',
          },
        ],
      },
      rules: [{ required: true, message: '请选择是否与模板同步', trigger: ['change', 'blur'] }],
    },
  ];

  let activeKey = ref('');
  // updateSchema 重置表单
  // validateFields 手动校验
  // clearValidate 清空校验
  // getFieldsValue 获取表单
  const [
    registerFormByDrive,
    {
      updateSchema: updateSchemaByDrive,
      validateFields: validateFieldsByDrive,
      setFieldsValue: setFieldsValueByDrive,
      removeSchemaByField: removeSchemaByFieldByDrive,
      appendSchemaByField: appendSchemaByFieldByDrive,
      resetFields: resetFieldsByDrive,
    },
  ] = useForm({
    labelWidth: 120,
    schemas: schemasByDrive,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });
  // 节点
  let nodeKey = '';
  const [register] = useModal();
  const { t } = useI18n();

  const emit = defineEmits(['submitSuccess']);

  let modalTitle = computed(() => {
    return `${
      props.formType.operationType === 0
        ? '新增'
        : props.formType.operationType === 1
        ? '编辑'
        : '查看'
    }${`${props.type === 'template' ? '模板' : ''}设备配置`}`;
  });

  interface TemplateOption {
    TemplateId: number;
    PreDriverName: string;
    AssemblyName: string;
    AddressExtend: string;
    ClassFullName: string;
    Description: string;
    DriverNO: string;
    PDU: string;
    Argument: any;
  }

  // 初始化
  async function initData() {
    nodeKey = props.formType.nodeName;
    let resByCascader = await getDefaultDriverConfig();

    workModelOptions = await getworkmodel();
    plcpathtypeOptions = await getplcpathtype();
    templateOptions = await gettemplatecollection();
    nextTick(() => {
      updateSchemaByDrive({
        field: 'TemplateId',
        componentProps: {
          options: templateOptions,
        },
      });
      updateSchemaByDrive({
        field: 'preconfiguration',
        componentProps: {
          disabled: props.type === 'template',
          options: resByCascader,
        },
      });
    });
    if (props.formType.id) {
      try {
        let res: any = await props.formType.getDriverInfo([props.formType.id]);
        // 添加表单值
        nodeKey = res.NodeKey;
        let setValue = {
          preconfiguration: JSON.parse(res.PreDriverName),
          name: res.Name,
          assemblyName: res.AssemblyName,
          addressExtend: res.AddressExtend,
          className: res.ClassFullName,
          Description: res.Description,
          TemplateId: res.TemplateId,
          TemplateSync: res.TemplateSync ? '1' : '0',
          DriverNO: res.DriverNO || buildUUID(),
          PDU: res.PDU,
        };
        setFieldsItem(res, setValue);
        delFields(res.Argument);
      } catch (error) {}
    }
  }
  // 根据模板设置表单值
  function setFieldsValueByTemplate(id) {
    if ([1, 2].indexOf(props.formType.operationType) >= 0) return;
    let targetVals = templateOptions.filter((item: any) => item.TemplateId === id);
    if (targetVals.length > 0) {
      let info = targetVals[0] as any;
      let setValue = {
        preconfiguration: JSON.parse(info.PreDriverName),
        assemblyName: info.AssemblyName,
        addressExtend: info.AddressExtend,
        className: info.ClassFullName,
        Description: info.Description,
        DriverNO: info.DriverNO,
        PDU: info.PDU,
      };
      setFieldsItem(info, setValue);
      delFields(info.Argument);
    }
  }
  // 动态加载表单
  function setNewForm(val) {
    if (val.Id) {
      // 添加表单值
      let setValue = {
        assemblyName: val.AssemblyName,
        addressExtend: val.AddressExtend,
        className: val.ClassFullName,
        PDU: val.PDU,
      };
      setFieldsItem(val, setValue);
      // 删除表单
      delFields(val.Argument);
    }
  }

  // 检查文档模式表单内容是否存在未填写项
  async function checkFileAnalysisForm(vals) {
    // 存在未填项的tab
    let lastKey = '';
    // 未填项的验证方法
    let lastValidate;
    // 是否校验成功
    return new Promise<ResByFileModel>(async (resolve) => {
      if (fileAnalysisArr.length === 0) {
        resolve({ isCheck: true, val: [] });
        return;
      }
      try {
        const values: Recordable = {};
        for (const item of fileAnalysisArr) {
          lastKey = item.Title;
          const { validate } = item.Form[1];
          lastValidate = validate;
          let resByVal = await validate();
          // 表单已支持多级key
          Object.assign(values, resByVal);
        }
        let newVals = cloneDeep(vals);
        let list = newVals.FileAnalysis || [];
        list.forEach((item) => {
          for (let keyb in values) {
            let names = keyb.split('.');
            if (names[0] && names.length === 2 && item.Title === names[0]) {
              item[names[1]] = values[keyb];
            } else if (names[0] && names.length === 3 && item.Title === names[0]) {
              item[names[1]][names[2]] = values[keyb];
            }
          }
          delete item.Divider;
          delete item.Form;
          delete item.Field;
        });
        resolve({ isCheck: true, val: list });
      } catch (e) {
        // 验证失败或出错，切换到对应标签页
        activeKey.value = lastKey;
        resolve({ isCheck: false, val: [] });

        if (Object.prototype.toString.call(e) === '[object Object]') {
          getFormErrorMessage(e);
        } else {
          // 加个计时器，先等表单示例渲染，再触发验证方法
          setTimeout(async () => {
            try {
              await lastValidate();
            } catch (error) {
              if (Object.prototype.toString.call(error) === '[object Object]') {
                getFormErrorMessage(error);
              }
            }
          }, 500);
        }
      }
    });
  }

  // 提交
  async function handleSubmint() {
    try {
      let res: any = {};
      let resByApi: any = {};
      res = await validateFieldsByDrive();
      let resByFile: ResByFileModel = await checkFileAnalysisForm(res);
      if (!resByFile.isCheck) return false;
      let params: ParamsByDriveModel = {
        Name: res.name,
        AssemblyName: res.assemblyName,
        AddressExtend: res.addressExtend,
        ClassFullName: res.className,
        PreDriverName: JSON.stringify(res.preconfiguration),
        Argument: oldArgument,
        TemplateId: res.TemplateId,
        TemplateSync: +res.TemplateSync === 1,
        Description: res.Description,
        DriverNO: res.DriverNO,
        PDU: res.PDU,
      };
      resByApi.Name = res.name;
      for (let key in params.Argument) {
        if (key === 'FileAnalysis') {
          params.Argument[key].FileAnalysis = resByFile.val;
        } else {
          if (props.type === 'template') {
            if (res[key].length >= 1 && typeof res[key] === 'object') {
              res[key].forEach((v, i) => {
                if (i === 0) {
                  params.Argument[key].ValueSync = v.filter((item) => +item === 1).length > 0;
                } else {
                  params.Argument[key].Value = v;
                }
              });
            }
          } else {
            params.Argument[key].Value = res[key];
          }
        }
      }
      if (nodeKey) params.nodeKey = nodeKey;
      if (props.formType.id) {
        let resByUpdate = await props.formType.updateDriverInfo([props.formType.id, params]);
        resByApi.Key = resByUpdate;
      } else {
        await props.formType.addDriver([params]);
      }
      createMessage.success(t('layout.setting.operatingTitle'));
      emit('submitSuccess', resByApi);
    } catch (error) {
      getFormErrorMessage(error);
    }
  }

  // 添加表单和添加表单值
  function setFieldsItem(item, setValue) {
    // 添加表单
    let newSetValue = setValue;
    if (props.type === 'template') {
      newSetValue = getSetValueByTemplate(item, setValue);
    } else {
      newSetValue = getSetValueByEquipment(item, setValue);
    }
    setFieldsValueByDrive(newSetValue);
    setTimeout(() => {
      handleSetValues();
    }, 500);
  }
  // 设置默认值
  async function handleSetValues() {
    for (const item of fileAnalysisArr) {
      const { setFieldsValue } = item.Form[1];

      await setFieldsValue(
        omit(item.Field, [
          `${item.Title}.DataFileConfig.Divider`,
          `${item.Title}.HistoryFileConfig.Divider`,
          `${item.Title}.Divider`,
        ]),
      );
    }
  }
  // 删除表单
  function delFields(Argument) {
    if (JSON.stringify(oldArgument) !== '{}') {
      let removeList: any[] = [];
      for (let keyx in oldArgument) {
        removeList.push(keyx);
      }
      removeSchemaByFieldByDrive(removeList);
    }
    oldArgument = Argument;
  }
  // 弹窗显示和关闭的钩子
  function handleVisibleChange(visible) {
    if (visible) {
      initData();
    } else {
      delFields({});
      resetFieldsByDrive();
    }
  }
  // 获取需要设置的表单（设备专用）
  function getSetValueByEquipment(item, setValue) {
    for (const key in item.Argument) {
      setValue[key] = item.Argument[key]['Value'];
      let fieldItem: FormSchema;
      switch (+item.Argument[key]['Type']) {
        case 3:
          fieldItem = {
            field: key,
            component: 'Select',
            label: item.Argument[key]['Description'] + '：',
            colProps: {
              span: 24,
            },
            dynamicDisabled: () => {
              return props.formType.operationType === 2;
            },
            componentProps: {
              disabled: item.Argument[key]['ValueSync'] && item.TemplateId,
              options: item.Argument[key]['DropList'] || [],
              fieldNames: { label: 'Name', value: 'Value', key: 'Key' },
            },
            rules: [
              {
                required: item.Argument[key]['Required'],
                // message: '请选择预配置',
                validator: async (_rule, value) =>
                  checkVaid(
                    value,
                    '请选择' + item.Argument[key]['Description'],
                    item.Argument[key]['Required'],
                  ),
                trigger: ['change', 'blur'],
              },
            ],
          };
          break;
        case 5:
          fieldItem = {
            field: key,
            component: 'RadioGroup',
            label: item.Argument[key]['Description'] + '：',
            colProps: {
              span: 24,
            },
            dynamicDisabled: () => {
              return props.formType.operationType === 2;
            },
            componentProps: {
              disabled: item.Argument[key]['ValueSync'] && item.TemplateId,
              options: [
                {
                  label: '是',
                  value: 'true',
                },
                {
                  label: '否',
                  value: 'false',
                },
              ],
            },
            rules: [
              {
                required: item.Argument[key]['Required'],
                // message: '请选择预配置',
                validator: async (_rule, value) =>
                  checkVaid(
                    value,
                    '请选择' + item.Argument[key]['Description'],
                    item.Argument[key]['Required'],
                  ),
                trigger: ['change', 'blur'],
              },
            ],
          };
          break;
        case 6:
          const valByFileAnalysis = item.Argument[key]['FileAnalysis'] || [];
          setValue[key] = valByFileAnalysis.map((item, index) => {
            const schemasByFileAnalysis: FormSchema[] = [];
            item.Field = {};
            const tabTitle = item.Title;
            if (index === 0) activeKey.value = tabTitle;
            // 日志
            const DataFileConfig = item.DataFileConfig || {};
            DataFileConfig['Divider'] = '';
            // 备份
            const HistoryFileConfig = item.HistoryFileConfig || {};
            HistoryFileConfig['Divider'] = '';
            item.Divider = '';
            const labelObj = {
              'DataFileConfig.Divider': {
                sort: 0,
                field: 'divider-basic',
                component: 'Divider',
                label: '日志',
                colProps: {
                  span: 24,
                },
                dynamicDisabled: () => {
                  return props.formType.operationType === 2;
                },
              },
              'DataFileConfig.PathType': {
                sort: 1,
                label: '类型：',
                component: 'Select',
                dynamicDisabled: () => {
                  return props.formType.operationType === 2;
                },
                componentProps: {
                  fieldNames: { label: 'Name', value: 'Value', key: 'Key' },
                  options: plcpathtypeOptions,
                },
                defaultValue: 0,
                rules: [
                  {
                    required: true,
                    // message: '请选择预配置',
                    validator: async (_rule, value) => checkVaid(value, '请选择类型', true),
                    trigger: ['change', 'blur'],
                  },
                ],
              },
              'DataFileConfig.LogLocation': {
                sort: 2,
                label: '位置：',
                component: 'Input',
                dynamicDisabled: () => {
                  return props.formType.operationType === 2;
                },
                rules: [
                  {
                    required: true,
                    validator: async (_rule, value) => checkVaid(value, '请输入位置', true),
                    trigger: ['change', 'blur'],
                  },
                ],
              },
              'DataFileConfig.UserName': {
                sort: 3,
                label: '用户名：',
                dynamicDisabled: () => {
                  return props.formType.operationType === 2;
                },
                component: 'Input',
                ifShow: ({ values }) => {
                  return values[`${tabTitle}.DataFileConfig.PathType`] === 1;
                },
              },
              'DataFileConfig.Password': {
                sort: 4,
                label: '密码：',
                component: 'Input',
                dynamicDisabled: () => {
                  return props.formType.operationType === 2;
                },
                ifShow: ({ values }) => {
                  return values[`${tabTitle}.DataFileConfig.PathType`] === 1;
                },
              },
              'HistoryFileConfig.Divider': {
                sort: 5,
                field: 'divider-basic',
                component: 'Divider',
                dynamicDisabled: () => {
                  return props.formType.operationType === 2;
                },
                label: '备份',
                colProps: {
                  span: 24,
                },
              },
              'HistoryFileConfig.PathType': {
                sort: 6,
                label: '类型：',
                component: 'Select',
                dynamicDisabled: () => {
                  return props.formType.operationType === 2;
                },
                componentProps: {
                  fieldNames: { label: 'Name', value: 'Value', key: 'Key' },
                  options: plcpathtypeOptions,
                },
                defaultValue: 0,
                rules: [
                  {
                    required: true,
                    // message: '请选择预配置',
                    validator: async (_rule, value) => checkVaid(value, '请选择类型', true),
                    trigger: ['change', 'blur'],
                  },
                ],
              },
              'HistoryFileConfig.LogLocation': {
                sort: 7,
                label: '位置：',
                component: 'Input',
                dynamicDisabled: () => {
                  return props.formType.operationType === 2;
                },
                rules: [
                  {
                    required: true,
                    validator: async (_rule, value) => checkVaid(value, '请输入位置', true),
                    trigger: ['change', 'blur'],
                  },
                ],
              },
              'HistoryFileConfig.UserName': {
                sort: 8,
                label: '用户名：',
                component: 'Input',
                dynamicDisabled: () => {
                  return props.formType.operationType === 2;
                },
                ifShow: ({ values }) => {
                  return values[`${tabTitle}.HistoryFileConfig.PathType`] === 1;
                },
              },
              'HistoryFileConfig.Password': {
                sort: 9,
                label: '密码：',
                component: 'Input',
                dynamicDisabled: () => {
                  return props.formType.operationType === 2;
                },
                ifShow: ({ values }) => {
                  return values[`${tabTitle}.HistoryFileConfig.PathType`] === 1;
                },
              },
              Divider: {
                sort: 10,
                field: 'divider-basic',
                component: 'Divider',
                label: '其它',
                colProps: {
                  span: 24,
                },
              },
              ReadCycle: {
                sort: 11,
                label: '读取周期：',
                dynamicDisabled: () => {
                  return props.formType.operationType === 2;
                },
                component: 'InputNumber',
                defaultValue: 0,
              },
              WorkModel: {
                sort: 12,
                label: '工作模式：',
                component: 'Select',
                dynamicDisabled: () => {
                  return props.formType.operationType === 2;
                },
                componentProps: {
                  fieldNames: { label: 'Name', value: 'Value', key: 'Key' },
                  options: workModelOptions,
                },
                defaultValue: 0,
              },
              LogExpireDay: {
                sort: 13,
                label: '日志过期天数：',
                dynamicDisabled: () => {
                  return props.formType.operationType === 2;
                },
                component: 'InputNumber',
                defaultValue: 0,
              },
              Extension: {
                sort: 13,
                label: '后缀：',
                dynamicDisabled: () => {
                  return props.formType.operationType === 2;
                },
                component: 'Input',
                defaultValue: 0,
              },
              Floor: {
                sort: 14,
                label: '层级：',
                dynamicDisabled: () => {
                  return props.formType.operationType === 2;
                },
                component: 'InputNumber',
                defaultValue: 0,
              },
              IsDbCache: {
                sort: 15,
                label: '是否存档：',
                dynamicDisabled: () => {
                  return props.formType.operationType === 2;
                },
                component: 'RadioGroup',
                defaultValue: true,
                componentProps: {
                  options: [
                    {
                      label: '是',
                      value: true,
                    },
                    {
                      label: '否',
                      value: false,
                    },
                  ],
                },
              },
              IsBackup: {
                sort: 15,
                label: '是否备份：',
                dynamicDisabled: () => {
                  return props.formType.operationType === 2;
                },
                component: 'RadioGroup',
                defaultValue: true,
                componentProps: {
                  options: [
                    {
                      label: '是',
                      value: true,
                    },
                    {
                      label: '否',
                      value: false,
                    },
                  ],
                },
              },
            };
            // 设置日志表单
            if (DataFileConfig.IsEnabled) {
              for (const keys in DataFileConfig) {
                if (labelObj[`DataFileConfig.${keys}`]) {
                  // 为后续的赋默认值做准备
                  item.Field[`${tabTitle}.DataFileConfig.${keys}`] = DataFileConfig[keys];
                  schemasByFileAnalysis.push({
                    field: `${tabTitle}.DataFileConfig.${keys}`,
                    colProps: { span: 24 },
                    ...labelObj[`DataFileConfig.${keys}`],
                  });
                }
              }
            }
            // 设置备份表单
            if (HistoryFileConfig.IsEnabled) {
              for (const keyx in HistoryFileConfig) {
                if (labelObj[`HistoryFileConfig.${keyx}`]) {
                  // 为后续的赋默认值做准备
                  item.Field[`${tabTitle}.HistoryFileConfig.${keyx}`] = HistoryFileConfig[keyx];
                  schemasByFileAnalysis.push({
                    field: `${tabTitle}.HistoryFileConfig.${keyx}`,
                    colProps: { span: 24 },
                    ...labelObj[`HistoryFileConfig.${keyx}`],
                  });
                }
              }
            }
            //设置其它表单
            for (const keyw in item) {
              if (labelObj[keyw]) {
                // 为后续的赋默认值做准备
                item.Field[`${tabTitle}.${keyw}`] = item[keyw];
                schemasByFileAnalysis.push({
                  field: `${tabTitle}.${keyw}`,
                  colProps: { span: 24 },
                  ...labelObj[keyw],
                });
              }
            }
            schemasByFileAnalysis.sort((a, b) => {
              return a.sort - b.sort;
            });
            const baseFormConfig = {
              labelWidth: 120,
              showActionButtonGroup: false,
              actionColOptions: {
                span: 24,
              },
            };
            item.Form = useForm(
              Object.assign({ schemas: schemasByFileAnalysis }, baseFormConfig) as FormProps,
            );
            return item;
          });
          fileAnalysisArr = setValue[key];
          fieldItem = {
            field: key,
            component: 'Input',
            dynamicDisabled: () => {
              return props.formType.operationType === 2;
            },
            label: item.Argument[key]['Description'] + '：',
            slot: 'slotTabsForm',
            colProps: {
              span: 24,
            },
          };
          break;
        default:
          fieldItem = {
            field: key,
            component: 'Input',
            dynamicDisabled: () => {
              return props.formType.operationType === 2;
            },
            label: item.Argument[key]['Description'] + '：',
            colProps: {
              span: 24,
            },
            rules: [
              {
                required: item.Argument[key]['Required'],
                // message: '请选择预配置',
                validator: (_rule, value) =>
                  +item.Argument[key]['CheckType'] === 1
                    ? checkIp(
                        value,
                        item.Argument[key]['Description'],
                        item.Argument[key]['Required'],
                      )
                    : checkVaid(
                        value,
                        '请输入' + item.Argument[key]['Description'],
                        item.Argument[key]['Required'],
                      ),
                trigger: ['change', 'blur'],
              },
            ],
            componentProps: {
              placeholder: '请输入' + item.Argument[key]['Description'],
              disabled: item.Argument[key]['ValueSync'] && item.TemplateId,
            },
          };
          break;
      }
      appendSchemaByFieldByDrive(fieldItem, '');
    }

    updateSchemaByDrive({
      field: 'preconfiguration',
      componentProps: {
        disabled: ['', null, undefined].indexOf(item.TemplateId) === -1,
      },
    });

    return setValue;
  }
  // 获取需要设置的表单（模板专用）
  function getSetValueByTemplate(item, setValue) {
    for (const key in item.Argument) {
      setValue[key] = [item.Argument[key]['ValueSync'] ? ['1'] : [], item.Argument[key]['Value']];
      let fieldItem: FormSchema;
      switch (+item.Argument[key]['Type']) {
        case 3:
          fieldItem = {
            field: key,
            component: 'CheckBoxSelect',
            label: item.Argument[key]['Description'] + '：',
            colProps: {
              span: 24,
            },
            componentProps: {
              leftStyle: 'width: 30%;',
              rightStyle: 'width: 70%;',
              selectOptions: item.Argument[key]['DropList'] || [],
              checkBoxOptions: [{ value: '1', label: '是否同步' }],
              fieldNamesBySelect: { label: 'Name', value: 'Value', key: 'Key' },
            },
            rules: [
              {
                required: item.Argument[key]['Required'],
                // message: '请选择预配置',
                validator: async (_rule, value) =>
                  checkVaid(
                    value.length >= 1 ? value[1] : '',
                    '请选择' + item.Argument[key]['Description'],
                    item.Argument[key]['Required'],
                  ),
                trigger: ['change', 'blur'],
              },
            ],
          };
          break;
        case 5:
          fieldItem = {
            field: key,
            component: 'CheckBoxRadio',
            label: item.Argument[key]['Description'] + '：',
            colProps: {
              span: 24,
            },
            componentProps: {
              leftStyle: 'width: 30%;',
              rightStyle: 'width: 70%;',
              checkBoxOptions: [{ value: '1', label: '是否同步' }],
              radioOptions: [
                {
                  label: '是',
                  value: 'true',
                },
                {
                  label: '否',
                  value: 'false',
                },
              ],
            },
            rules: [
              {
                required: item.Argument[key]['Required'],
                // message: '请选择预配置',
                validator: async (_rule, value) =>
                  checkVaid(
                    value.length >= 1 ? value[1] : '',
                    '请选择' + item.Argument[key]['Description'],
                    item.Argument[key]['Required'],
                  ),
                trigger: ['change', 'blur'],
              },
            ],
          };
          break;
        case 6:
          const valByFileAnalysis = item.Argument[key]['FileAnalysis'] || [];
          setValue[key] = valByFileAnalysis.map((item, index) => {
            const schemasByFileAnalysis: FormSchema[] = [];
            item.Field = {};
            const tabTitle = item.Title;
            if (index === 0) activeKey.value = tabTitle;
            // 日志
            const DataFileConfig = item.DataFileConfig || {};
            DataFileConfig['Divider'] = '';
            // 备份
            const HistoryFileConfig = item.HistoryFileConfig || {};
            HistoryFileConfig['Divider'] = '';
            item.Divider = '';
            const labelObj = {
              'DataFileConfig.Divider': {
                sort: 0,
                field: 'divider-basic',
                component: 'Divider',
                label: '日志',
                colProps: {
                  span: 24,
                },
              },
              'DataFileConfig.PathType': {
                sort: 1,
                label: '类型：',
                component: 'Select',
                componentProps: {
                  fieldNames: { label: 'Name', value: 'Value', key: 'Key' },
                  options: plcpathtypeOptions,
                },
                defaultValue: 0,
                rules: [
                  {
                    required: true,
                    // message: '请选择预配置',
                    validator: async (_rule, value) => checkVaid(value, '请选择类型', true),
                    trigger: ['change', 'blur'],
                  },
                ],
              },
              'DataFileConfig.LogLocation': {
                sort: 2,
                label: '位置：',
                component: 'Input',
                rules: [
                  {
                    required: true,
                    validator: async (_rule, value) => checkVaid(value, '请输入位置', true),
                    trigger: ['change', 'blur'],
                  },
                ],
              },
              'DataFileConfig.UserName': {
                sort: 3,
                label: '用户名：',
                component: 'Input',
                ifShow: ({ values }) => {
                  return values[`${tabTitle}.DataFileConfig.PathType`] === 1;
                },
              },
              'DataFileConfig.Password': {
                sort: 4,
                label: '密码：',
                component: 'Input',
                ifShow: ({ values }) => {
                  return values[`${tabTitle}.DataFileConfig.PathType`] === 1;
                },
              },
              'HistoryFileConfig.Divider': {
                sort: 5,
                field: 'divider-basic',
                component: 'Divider',
                label: '备份',
                colProps: {
                  span: 24,
                },
              },
              'HistoryFileConfig.PathType': {
                sort: 6,
                label: '类型：',
                component: 'Select',
                componentProps: {
                  fieldNames: { label: 'Name', value: 'Value', key: 'Key' },
                  options: plcpathtypeOptions,
                },
                defaultValue: 0,
                rules: [
                  {
                    required: true,
                    // message: '请选择预配置',
                    validator: async (_rule, value) => checkVaid(value, '请选择类型', true),
                    trigger: ['change', 'blur'],
                  },
                ],
              },
              'HistoryFileConfig.LogLocation': {
                sort: 7,
                label: '位置：',
                component: 'Input',
                rules: [
                  {
                    required: true,
                    validator: async (_rule, value) => checkVaid(value, '请输入位置', true),
                    trigger: ['change', 'blur'],
                  },
                ],
              },
              'HistoryFileConfig.UserName': {
                sort: 8,
                label: '用户名：',
                component: 'Input',
                ifShow: ({ values }) => {
                  return values[`${tabTitle}.HistoryFileConfig.PathType`] === 1;
                },
              },
              'HistoryFileConfig.Password': {
                sort: 9,
                label: '密码：',
                component: 'Input',
                ifShow: ({ values }) => {
                  return values[`${tabTitle}.HistoryFileConfig.PathType`] === 1;
                },
              },
              Divider: {
                sort: 10,
                field: 'divider-basic',
                component: 'Divider',
                label: '其它',
                colProps: {
                  span: 24,
                },
              },
              ReadCycle: {
                sort: 11,
                label: '读取周期：',
                component: 'InputNumber',
                defaultValue: 0,
              },
              WorkModel: {
                sort: 12,
                label: '工作模式：',
                component: 'Select',
                componentProps: {
                  fieldNames: { label: 'Name', value: 'Value', key: 'Key' },
                  options: workModelOptions,
                },
                defaultValue: 0,
              },
              LogExpireDay: {
                sort: 13,
                label: '日志过期天数：',
                component: 'InputNumber',
                defaultValue: 0,
              },
              Extension: {
                sort: 13,
                label: '后缀：',
                component: 'Input',
                defaultValue: 0,
              },
            };
            // 设置日志表单
            if (DataFileConfig.IsEnabled) {
              for (const keys in DataFileConfig) {
                if (labelObj[`DataFileConfig.${keys}`]) {
                  // 为后续的赋默认值做准备
                  item.Field[`${tabTitle}.DataFileConfig.${keys}`] = DataFileConfig[keys];
                  schemasByFileAnalysis.push({
                    field: `${tabTitle}.DataFileConfig.${keys}`,
                    colProps: { span: 24 },
                    ...labelObj[`DataFileConfig.${keys}`],
                  });
                }
              }
            }
            // 设置备份表单
            if (HistoryFileConfig.IsEnabled) {
              for (const keyx in HistoryFileConfig) {
                if (labelObj[`HistoryFileConfig.${keyx}`]) {
                  // 为后续的赋默认值做准备
                  item.Field[`${tabTitle}.HistoryFileConfig.${keyx}`] = HistoryFileConfig[keyx];
                  schemasByFileAnalysis.push({
                    field: `${tabTitle}.HistoryFileConfig.${keyx}`,
                    colProps: { span: 24 },
                    ...labelObj[`HistoryFileConfig.${keyx}`],
                  });
                }
              }
            }
            //设置其它表单
            for (const keyw in item) {
              if (labelObj[keyw]) {
                // 为后续的赋默认值做准备
                item.Field[`${tabTitle}.${keyw}`] = item[keyw];
                schemasByFileAnalysis.push({
                  field: `${tabTitle}.${keyw}`,
                  colProps: { span: 24 },
                  ...labelObj[keyw],
                });
              }
            }
            schemasByFileAnalysis.sort((a, b) => {
              return a.sort - b.sort;
            });
            const baseFormConfig = {
              labelWidth: 120,
              showActionButtonGroup: false,
              actionColOptions: {
                span: 24,
              },
            };
            item.Form = useForm(
              Object.assign({ schemas: schemasByFileAnalysis }, baseFormConfig) as FormProps,
            );
            return item;
          });
          fileAnalysisArr = setValue[key];
          fieldItem = {
            field: key,
            component: 'Input',
            label: item.Argument[key]['Description'] + '：',
            slot: 'slotTabsForm',
            colProps: {
              span: 24,
            },
          };
          break;
        default:
          fieldItem = {
            field: key,
            component: 'InputCheckbox',
            label: item.Argument[key]['Description'] + '：',
            colProps: {
              span: 24,
            },
            rules: [
              {
                required: item.Argument[key]['Required'],
                // message: '请选择预配置',
                validator: (_rule, value) =>
                  +item.Argument[key]['CheckType'] === 1
                    ? checkIp(
                        value.length >= 1 ? value[1] : '',
                        item.Argument[key]['Description'],
                        item.Argument[key]['Required'],
                      )
                    : checkVaid(
                        value.length >= 1 ? value[1] : '',
                        '请输入' + item.Argument[key]['Description'],
                        item.Argument[key]['Required'],
                      ),
                trigger: ['change', 'blur'],
              },
            ],
            componentProps: {
              ipnutPlaceholder: '请输入' + item.Argument[key]['Description'],
              options: [{ value: '1', label: '是否同步' }],
              leftStyle: 'width: 30%;',
              rightStyle: 'width: 70%;',
            },
          };
          break;
      }

      appendSchemaByFieldByDrive(fieldItem, '');
    }
    return setValue;
  }
</script>

<style scoped lang="less">
  .tabs-form {
    width: 100%;
    padding: 5px 10px;
    box-sizing: border-box;
    border: 1px solid #d9d9d9;
    border-radius: 2px;
  }

  ::v-deep(.ant-cascader-menu) {
    height: 300px;
  }
</style>
